package project_38;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 张杰
 * Date: 2022-03-08
 * Time: 14:55
 */
public class TestHeap {
    public int[] elem;
    public int usedSize;

    public TestHeap() {
        this.elem = new int[10];
    }

    /* 调整二叉树成为大根堆
     * @author zj
     * @date 2022/3/7
     * @param parent  每棵树的根节点
     * @param len  每棵树调整的结束位置
     */
    public void shiftDown(int parent,int len) {
        int child =  2*parent + 1;
        while(child < len) {
            if(child+1 < len && elem[child] < elem[child+1]) {
                child++;
            }
            if(elem[child] > elem[parent]) {
                int tmp = elem[child];
                elem[child] = elem[parent];
                elem[parent] = tmp;
                parent = child;
                child = 2*parent+1;
            }else {
                break;
            }
        }
    }
    public void creatBigHeap(int[] array) {
        for(int i = 0; i < array.length;i++) {
            elem[i] = array[i];
            usedSize++;
        }
        for(int parent = (usedSize-1-1)/2; parent >= 0; parent--) {
            shiftDown(parent,usedSize);
        }
    }

    private void shiftUp(int child){
        int parent = (child-1) / 2;
        while(parent >= 0 ) {
            if(elem[child] > elem[parent]) {
                int tmp = elem[child];
                elem[child] = elem[parent];
                elem[parent] = tmp;
                child = parent;
                parent = (parent-1) / 2;
            }else {
                break;
            }
        }

    }
    /*
     * @author zj
     * @date 2022/3/8
     * @param val
     */
    public void offer(int val) {
        if(isFull()) {
            //扩容
            elem = Arrays.copyOf(elem,2*elem.length);
        }
        elem[usedSize++] = val;
        //向上调整
        shiftUp(usedSize-1);
    }

    public boolean isFull() {
        return this.usedSize == elem.length;
    }

    public int poll() {
        if(isEmpty()) {
            throw new RuntimeException("优先级队列为空！");
        }
        int tmp = elem[0];
        elem[0] = elem[usedSize-1];
        elem[usedSize-1] = tmp;
        usedSize--;
        shiftDown(0,usedSize);
        return tmp;
    }
    public boolean isEmpty() {
        return usedSize == 0;
    }

    public int peek() {
        if(isEmpty()) {
            throw new RuntimeException("优先级队列为空！");
        }

        return elem[0];
    }

    /* 堆排序
     * @author zj
     * @date 2022/3/8
     * @param
    */
    public  void heapSort() {
        int end = this.usedSize - 1;
        while(end > 0) {
            int tmp = elem[0];
            elem[0] = elem[end];
            elem[end] = tmp;
            shiftDown(0,end);
            end--;
        }
    }
}
